#include "Stdafx.h"
#include "wruntime_error.h"
#include <vector>

using namespace std;

	wruntime_error::wruntime_error(const wstring& errorMsg)
		: runtime_error(to_narrow_string(errorMsg))
		, mErrorMsg(errorMsg)
	{
		// NOTE: We give the runtime_error base the narrow version of the 
		//  error message. This is what will get shown if what() is called.
		//  The wruntime_error inserter or errorMsg() should be used to get 
		//  the wide version.
	}

	/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */

	wruntime_error::wruntime_error(const wruntime_error& rhs)
		: runtime_error(to_narrow_string(rhs.errorMsg()))
		, mErrorMsg(rhs.errorMsg())
	{
	}

	/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */

	wruntime_error&
		wruntime_error::operator=(const wruntime_error& rhs)
	{
		// copy the wruntime_error
		runtime_error::operator=(rhs);
		mErrorMsg = rhs.mErrorMsg;

		return *this;
		}

	/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */

	wruntime_error::~wruntime_error()
	{
	}

	/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */

	const wstring& wruntime_error::errorMsg() const { return mErrorMsg; }

	std::string to_narrow_string(std::wstring const& text)
	{
		std::locale const loc("");
		wchar_t const* from = text.c_str();
		std::size_t const len = text.size();
		std::vector<char> buffer(len + 1);
		std::use_facet<std::ctype<wchar_t> >(loc).narrow(from, from + len, '_', &buffer[0]);
		return std::string(&buffer[0], &buffer[len]);
	}

	std::wstring to_wide_string(std::string const& text)
	{
		std::locale const loc("");
		char const* from = text.c_str();
		std::size_t const len = text.size();
		std::vector<wchar_t> buffer(len + 1);
		std::use_facet<std::ctype<wchar_t> >(loc).widen(from, from + len,  &buffer[0]);
		return std::wstring(&buffer[0], &buffer[len]);
	}
